<template> 
    <view class="case-detail-container">
        <!-- 顶部导航栏 -->
        <view class="nav-bar">
            <text class="nav-title">案例详情</text>
            <view class="share-icon" @click="shareCase">
                <text class="icon-share">分享</text>
            </view>
        </view>
        
        <!-- 加载状态 -->
        <view class="loading-state" v-if="loading">
            <view class="loading-spinner"></view>
            <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 错误提示 -->
        <view class="error-state" v-else-if="errorMsg">
            <text class="error-text">{{ errorMsg }}</text>
            <button class="retry-btn" @click="fetchCaseDetail">重试</button>
        </view>
        
        <!-- 案例内容 -->
        <view class="case-content" v-else-if="caseDetail">
            <!-- 图片轮播 -->
            <swiper class="image-swiper" 
                :indicator-dots="true" 
                :autoplay="true" 
                :interval="3000" 
                :duration="500"
                indicator-active-color="#A259FF"
                indicator-color="rgba(255,255,255,0.5)"
                v-if="caseDetail.imageList && caseDetail.imageList.length > 0"
            >
                <swiper-item v-for="(image, index) in caseDetail.imageList" :key="index">
                    <image :src="image" mode="aspectFill" class="swiper-image" @click="previewImage(index)"></image>
                </swiper-item>
            </swiper>
            
            <!-- 无图片占位 -->
            <view class="no-image" v-else>
                <text class="no-image-text">暂无图片</text>
            </view>
            
            <!-- 基本信息 -->
            <view class="info-section">
                <view class="case-title">{{ caseDetail.title }}</view>
                <view class="case-price">¥{{ formatPrice(caseDetail.price) }}</view>
                
                <view class="divider"></view>
                
                <view class="section-title">案例介绍</view>
                <view class="case-introduce">{{ caseDetail.introduce || '暂无介绍' }}</view>
                
                <view class="divider"></view>
                
                <!-- 创建时间 -->
                <view class="case-time" v-if="caseDetail.createdTime">
                    <text class="time-label">发布时间：</text>
                    <text class="time-value">{{ formatDate(caseDetail.createdTime) }}</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/request';

// 响应式数据
const caseDetail = ref(null);
const loading = ref(true);
const errorMsg = ref('');
const caseId = ref('');

// 页面加载初始化
const initPage = () => {
    try {
        // 尝试从onLoad中获取参数
        const onLoadOptions = uni.getStorageSync('case_detail_options');
        if (onLoadOptions && onLoadOptions.id) {
            caseId.value = onLoadOptions.id;
            fetchCaseDetail();
            return;
        }
        
        // 获取当前页面路由
        const pages = getCurrentPages();
        if (!pages || pages.length === 0) {
            showError('无法获取页面参数');
            return;
        }
        
        const currentPage = pages[pages.length - 1];
        
        // 尝试多种方式获取页面参数
        if (currentPage.options && currentPage.options.id) {
            caseId.value = currentPage.options.id;
            fetchCaseDetail();
            return;
        }
        
        if (currentPage.$page && currentPage.$page.options && currentPage.$page.options.id) {
            caseId.value = currentPage.$page.options.id;
            fetchCaseDetail();
            return;
        }
        
        // 尝试从URL中解析
        const fullPath = currentPage.$page?.fullPath || currentPage.route;
        if (fullPath && fullPath.includes('?')) {
            const queryString = fullPath.split('?')[1];
            const params = new URLSearchParams(queryString);
            caseId.value = params.get('id') || '';
            
            if (caseId.value) {
                fetchCaseDetail();
                return;
            }
        }
        
        showError('案例ID不存在');
    } catch (error) {
        showError('初始化页面失败');
    }
};

// 显示错误
const showError = (msg) => {
    errorMsg.value = msg || '加载失败';
    loading.value = false;
};

// 获取案例详情
const fetchCaseDetail = async () => {
    loading.value = true;
    errorMsg.value = '';
    
    try {
        const res = await request('/case/detail', {
            method: 'GET',
            data: {
                id: caseId.value
            }
        });
        
        if (res.code === 200 && res.data) {
            caseDetail.value = res.data;
            // 确保imageList是数组
            if (!Array.isArray(caseDetail.value.imageList)) {
                caseDetail.value.imageList = [];
            }
        } else {
            showError(res.msg || '获取案例详情失败');
        }
    } catch (error) {
        showError('网络错误，请稍后重试');
    } finally {
        loading.value = false;
    }
};

// 预览图片
const previewImage = (index) => {
    if (!caseDetail.value || !caseDetail.value.imageList || caseDetail.value.imageList.length === 0) return;
    
    uni.previewImage({
        current: index,
        urls: caseDetail.value.imageList
    });
};

// 分享案例
const shareCase = () => {
    if (!caseDetail.value) return;
    
    // 在小程序环境下使用小程序的分享API
    if (uni.canIUse('button.open-type.share')) {
        uni.showToast({
            title: '点击右上角分享给好友',
            icon: 'none'
        });
    } else {
        // 在H5等环境下可以使用系统分享或复制链接
        uni.setClipboardData({
            data: `${caseDetail.value.title} - 查看详情: ${window.location.href}`,
            success: () => {
                uni.showToast({
                    title: '链接已复制，请粘贴分享',
                    icon: 'none'
                });
            }
        });
    }
};

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '未知';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化价格
const formatPrice = (price) => {
    if (price === null || price === undefined) return '0.00';
    return Number(price).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

// 页面加载函数
onMounted(() => {
    initPage();
});

// 定义onLoad生命周期函数，用于接收页面参数
defineExpose({
    onLoad: (options) => {
        if (options && options.id) {
            // 将参数存储到本地，以便在mounted中使用
            uni.setStorageSync('case_detail_options', options);
            caseId.value = options.id;
        }
    },
    // 小程序分享功能
    onShareAppMessage: () => {
        if (!caseDetail.value) return {};
        
        return {
            title: caseDetail.value.title,
            path: `/pages/index/case-detail?id=${caseId.value}`,
            imageUrl: caseDetail.value.imageList && caseDetail.value.imageList.length > 0 
                ? caseDetail.value.imageList[0] 
                : ''
        };
    }
});
</script>

<style lang="scss" scoped>
.case-detail-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #18122B 0%, #120C1C 100%);
    padding-bottom: 40rpx;
}

/* 导航栏样式 */
.nav-bar {
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #2D1457;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.nav-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #A259FF;
}

.share-icon {
    background: linear-gradient(45deg, #7B2FF2, #10AEFF);
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
    font-size: 26rpx;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
}

.icon-share {
    margin-left: 6rpx;
}

/* 加载状态 */
.loading-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 400rpx;
}

.loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid rgba(162, 89, 255, 0.2);
    border-top: 4rpx solid #A259FF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
}

.loading-text {
    font-size: 28rpx;
    color: #B8B8D1;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* 错误状态 */
.error-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 400rpx;
}

.error-text {
    font-size: 28rpx;
    color: #ff6b6b;
    margin-bottom: 30rpx;
}

.retry-btn {
    background: linear-gradient(45deg, #7B2FF2, #10AEFF);
    color: #fff;
    font-size: 28rpx;
    padding: 10rpx 40rpx;
    border-radius: 30rpx;
    border: none;
}

/* 案例内容 */
.case-content {
    padding-bottom: 40rpx;
}

/* 图片轮播 */
.image-swiper {
    width: 100%;
    height: 500rpx;
}

.swiper-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* 无图片占位 */
.no-image {
    width: 100%;
    height: 400rpx;
    background: rgba(45, 20, 87, 0.3);
    display: flex;
    justify-content: center;
    align-items: center;
}

.no-image-text {
    color: #B8B8D1;
    font-size: 28rpx;
}

/* 信息区域 */
.info-section {
    padding: 30rpx;
    background: linear-gradient(135deg, #221A36 0%, #18122B 100%);
    margin: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx #7B2FF244;
    border: 1px solid #2D1457;
}

.case-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 20rpx;
}

.case-price {
    font-size: 40rpx;
    color: #A259FF;
    font-weight: bold;
}

.divider {
    height: 1px;
    background: rgba(45, 20, 87, 0.5);
    margin: 30rpx 0;
}

.section-title {
    font-size: 32rpx;
    color: #A259FF;
    font-weight: bold;
    margin-bottom: 20rpx;
}

.case-introduce {
    font-size: 28rpx;
    color: #B8B8D1;
    line-height: 1.6;
    white-space: pre-wrap;
}

.case-time {
    margin-top: 20rpx;
    font-size: 24rpx;
    color: #B8B8D1;
}

.time-label {
    color: #7B2FF2;
}
</style>